package cn.fl.risk.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.service.IInsChnOpenSettingService;
import cn.fl.insurance.vo.OrgTreeVO;
import cn.fl.risk.condition.RskUsrOrgRQueryCondition;
import cn.fl.risk.service.IRskUsrOrgRService;
import cn.fl.risk.vo.RskUsrOrgRVO;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @Description: 租金提醒用户与组织架构关系表 控制层
 */
@Controller
@RequestMapping("/risk/rskUsrOrgR")
public class RskUsrOrgRController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(RskUsrOrgRController.class);

	/**
	 * RskUsrOrgR 服务层BEAN
	 */
	@Autowired
	private IRskUsrOrgRService rskUsrOrgRService;
	@Autowired
	private IInsChnOpenSettingService insChnOpenSettingService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toConfigPage.do", method = {RequestMethod.GET})
	public ModelAndView toConfigPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toConfigPage", "加载任务分配列表页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("risk/rskUsrOrgR/taskConfig");
		return mav;
	}

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载RskUsrOrgR列表页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("risk/rskUsrOrgR/rskUsrOrgRList");
		return mav;
	}

	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载RskUsrOrgR Add页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("risk/rskUsrOrgR/rskUsrOrgRModify");
		//this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载RskUsrOrgR Modify页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("risk/rskUsrOrgR/rskUsrOrgRModify");
		//this.prepare(request,mav);

		String id = request.getParameter("id");
		RskUsrOrgRVO rskUsrOrgRVO = this.rskUsrOrgRService.selectById(Long.valueOf(id));
		mav.addObject("rskUsrOrgRVO", rskUsrOrgRVO);
		return mav;
	}

	//加载数据字典数据、传值等 ？
	public void prepare(HttpServletRequest request, ModelAndView mav) {

	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
	@ResponseBody
	public Object initRskUsrOrgRList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		RskUsrOrgRQueryCondition qc = new RskUsrOrgRQueryCondition();
		//设置查询条件
		String rlNm = request.getParameter("rlNm");
		if (StringUtils.isNotEmpty(rlNm)) {
			qc.setRlNm(rlNm);
		}
		page.setCondition(qc);
		BaseLogUtils.info(logger, "initRskUsrOrgRList", "初始化RskUsrOrgR列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		Pager pager = this.rskUsrOrgRService.searchListPage(page);
		List<RskUsrOrgRVO> list = (List<RskUsrOrgRVO>) pager.getResultList();
		ListPageVO<RskUsrOrgRVO> listPage = new ListPageVO<RskUsrOrgRVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 初始化组织架构事业部树列表
	 */
	@RequestMapping(value = "/treeInitList.do", method = {RequestMethod.GET})
	@ResponseBody
	public Object treeInitList(HttpServletRequest request, HttpServletResponse response) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String orgNm = request.getParameter("orgNm");//组织架构名称
		if (StringUtils.isNotBlank(orgNm)) {
			List<OrgTreeVO> tvoList1 = this.rskUsrOrgRService.serchOrgTreeList(orgNm);
			if (tvoList1 == null) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getByOrgNm", "获取资源数据不存在.", CurrentThreadContext.getCurrentUserName());
			} else {
				BaseLogUtils.info(logger, "getByOrgNm", "加载资源树成功.", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(tvoList1);
			return result;
		} else {
			return this.insChnOpenSettingService.searchOrgTreeVOList(null);
		}

	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST})
	@ResponseBody
	public DataResultVO removeRskUsrOrgRByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if (StringUtils.isEmpty(ids)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removeRskUsrOrgRByIds", "删除RskUsrOrgR数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}

		try {
			boolean success = this.rskUsrOrgRService.removeByIds(idsList);
			if (!success) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeRskUsrOrgRByIds", "删除RskUsrOrgR数据失败,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeRskUsrOrgRByIds", "删除RskUsrOrgR数据成功,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removeRskUsrOrgRByIds", "删除RskUsrOrgR数据失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeRskUsrOrgRByIds", "删除RskUsrOrgR数据失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
	@ResponseBody
	public Object getRskUsrOrgRById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if (StringUtils.isEmpty(id)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getRskUsrOrgRById", "获取RskUsrOrgR数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		try {
			RskUsrOrgRVO vo = this.rskUsrOrgRService.selectById(Long.valueOf(id));
			if (null == vo) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getRskUsrOrgRById", "获取RskUsrOrgR数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getRskUsrOrgRById", "获取RskUsrOrgR数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getRskUsrOrgRById", "获取RskUsrOrgR数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getRskUsrOrgRById", "获取RskUsrOrgR数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = {RequestMethod.POST})
	@ResponseBody
	public Object addRskUsrOrgR(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String usrId = request.getParameter("usrId");//系统用户ID
		String[] orgCdArr = request.getParameterValues("orgCdArr[]");//组织架构代码
		List<String> orgCdList = new ArrayList<String>();
		if (orgCdArr != null && orgCdArr.length > 0) {
			Collections.addAll(orgCdList, orgCdArr);
		}
		if(CollectionUtils.isNotEmpty(orgCdList)){
			//验证参数并赋值
			RskUsrOrgRVO entity = null;
			List<RskUsrOrgRVO> rskUsrOrgRlist = new ArrayList<>(orgCdList.size());
			if (CollectionUtils.isNotEmpty(orgCdList)) {
				for (String idStr : orgCdList) {
					entity = new RskUsrOrgRVO();
					entity.setOrgCd(idStr);//组织架构代码
					if (StringUtils.isNotBlank(usrId)) {
						entity.setUsrId(Long.valueOf(usrId));//系统用户ID
					}
					rskUsrOrgRlist.add(entity);
				}
			}
			boolean flag = this.rskUsrOrgRService.addOrgr(rskUsrOrgRlist);
			if (flag) {
				BaseLogUtils.info(logger, "addRskUsrOrgR", "新增RskUsrOrgR数据成功.DATA:" + rskUsrOrgRlist,
						CurrentThreadContext.getCurrentUserName());
			} else {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "addRskUsrOrgR", "新增RskUsrOrgR数据失败",
						CurrentThreadContext.getCurrentUserName());
			}
		}else{
			List<Long> usrIdList = new ArrayList<>(1);
			if (StringUtils.isNotBlank(usrId)) {
				usrIdList.add(Long.valueOf(usrId));//系统用户ID
				boolean flag = this.rskUsrOrgRService.removeByIds(usrIdList);
				if (flag) {
					BaseLogUtils.info(logger, "addRskUsrOrgR", "删除RskUsrOrgR数据成功.DATA:" + usrIdList,
							CurrentThreadContext.getCurrentUserName());
				} else {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("系统异常");
					BaseLogUtils.info(logger, "addRskUsrOrgR", "删除RskUsrOrgR数据失败"+ usrIdList,CurrentThreadContext.getCurrentUserName());
				}
			}
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
	@ResponseBody
	public Object modifyRskUsrOrgR(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		RskUsrOrgRVO entity = null;
		try {
			entity = this.getRequestParamForRskUsrOrgR(request);
			if (entity.getId() == null) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifyRskUsrOrgR", "修改RskUsrOrgR信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}

			boolean success = this.rskUsrOrgRService.modify(entity);
			if (!success) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyRskUsrOrgR", "修改RskUsrOrgR数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifyRskUsrOrgR", "修改RskUsrOrgR数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
			BaseLogUtils.info(logger, "modifyRskUsrOrgR", "修改RskUsrOrgR数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
			BaseLogUtils.error(logger, "modifyRskUsrOrgR", "修改RskUsrOrgR数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 获取请求参数
	 *
	 * @param request 请求
	 * @return
	 */
	private RskUsrOrgRVO getRequestParamForRskUsrOrgR(HttpServletRequest request) throws BaseException {
		//获取参数
		String id = request.getParameter("id");//主键
		String usrId = request.getParameter("usrId");//系统用户ID
		//验证参数并赋值
		RskUsrOrgRVO entity = null;
		Date tm = new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(tm);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		} else {
			entity.setCrtTm(tm);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			//entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
			//entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
		}

		return entity;
	}
}

